export function ws(port, param) {
  // 创建WebSocket连接
  if (typeof port == "object") {
    port.send(JSON.stringify(param))
  }

  const socket =
    typeof port == "object" ? port : new WebSocket(`ws://localhost:${port}`)

  // 监听连接打开事件
  socket.onopen = () => {
    // console.log('WebSocket连接已打开')
    // 发送消息到服务器
    socket.send(JSON.stringify(param))
  }

  // 监听消息事件
  // socket.onmessage = event => {
  //     console.log('收到服务器消息: ', JSON.parse(event.data))
  // }

  // 监听连接关闭事件
  // socket.onclose = () => {
  //     console.log('WebSocket连接已关闭')
  // }

  socket.sender = param => {
    return ws(socket, param)
  }

  return new Promise(resolve => {
    socket.onmessage = event => {
      socket.msg = JSON.parse(event.data)
      // console.log('收到服务器消息: ', JSON.parse(event.data).msg)
      resolve(socket)
    }
  })
}
